#include "management.h"
#include "ui_management.h"
#include <QHeaderView>
#include <QMessageBox>
#include <QStandardItemModel>
#include "fileoperation.h"
management::management(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::management)
{
    ui->setupUi(this);
    // 设置窗口标题
    this->setWindowTitle("控制窗口");
    // 设置登录窗口无边框
    this->setWindowFlags(Qt::FramelessWindowHint);
    // 监听退出
    connect(ui->exit,&QPushButton::clicked, this, &management::close);
    // 设置标题
    ui->tabWidget->setTabText(0, "全部人员列表");
    ui->tabWidget->setTabText(1, "添加员工");
    ui->tabWidget->setTabText(2, "删除员工");
    ui->tabWidget->setStyleSheet("QTabWidget#tabWidget{background-color:rgb(255,0,0);}\
                            QTabBar::tab{background-color:rgb(220,200,180);color:rgb(0,0,0);font:8pt '黑体'}\
                            QTabBar::tab::selected{background-color:rgb(0,100,200);color:rgb(0,0,0);font:8pt '黑体'}");
    // 保存连接对象
    FileOperation *instance = FileOperation::getInstance();
    // 连接tcp服务端
    instance->readConif(&config);
    tcp_client = new TcpSocket(config.ip, config.port.toUInt());

    // 等待获取响应数据
    connect(tcp_client->m_tcp, &QTcpSocket::readyRead, this, [&]{
        // 获取server返回数据
        QByteArray rowData = tcp_client->readData();
        BaseModel md = BaseModel(rowData);
        switch (md.model) {
        case 1:
            parseModel1(rowData);
            break;
        case 2:
            parseModel2(rowData);
            break;
        case 3:
            parseModel2(rowData);
        case 4:
            emit is_login(parseModel2(rowData));
            break;
        }
    });
    // 右键设置
    m_action = new QAction("没有添加设置");
    // 窗口设置背景色
    setBackground();

    // 监听点击切换
    connect(ui->tabWidget, &QTabWidget::tabBarClicked, this, [&](int index){
        switch (index) {
        case 0:
            // 刷新全员表
            tcp_client->sendData(sendModel1());
            // 清空字段
            m_strList.clear();
            // 如果原本有数据需要释放
            delete item_mode;
            break;
        case 1:
            // 展示增加人员
            /* 创建数据模型 */
            QStandardItemModel* model = new QStandardItemModel();
            // 设置表头
            model->setHorizontalHeaderLabels(m_strList);
            for(int j = 0;j < m_strList.size(); j++)
            {
                model->setItem(0, j, new QStandardItem(""));
            }
            /* 自适应所有列，让它布满空间 */
            ui->creatPeople->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
            /* 设置表格视图大小 */
            ui->creatPeople->resize(850, 400);
            /* 设置表格视图数据 */
            ui->creatPeople->setModel(model);
            //设置自动排序
            ui->creatPeople->setSortingEnabled(true);
            // 隐藏行号
            QHeaderView* headerView = ui->creatPeople->verticalHeader();
            headerView->setHidden(true);
            break;
        }
    });

    // 监听保存人员按钮
    connect(ui->savePeople, &QPushButton::clicked, this, [&](){
        // 获取添加人员表格数据
        QStandardItemModel* model = (QStandardItemModel*)ui->creatPeople->model();
        tcp_client->sendData(sendModel2(model));
        // 弹出保存成功提示
        QMessageBox::information(nullptr,  "result",  "save ok!", QMessageBox::Yes, QMessageBox::Yes);
        // 清空数据
        for(int j = 0;j < m_strList.size(); j++)
        {
            model->setItem(0, j, new QStandardItem(""));
        }
    });

    // 监听删除按钮
    connect(ui->sendButton, &QPushButton::clicked, this, [&](){
        QString id = ui->lineEdit->text();
        tcp_client->sendData(sendModel3(id));
        // 弹出保存成功提示
        QMessageBox::information(nullptr,  "result",  "save ok!", QMessageBox::Yes, QMessageBox::Yes);
    });
}

management::~management()
{
    delete ui;
}

void management::setBackground()
{
    this->setAutoFillBackground(true);
    QPalette p = this->palette();
    // 设置背景图
    QPixmap pix(":/images/t2.jpeg");
    p.setBrush(QPalette::Window, QBrush(pix));
    // 设置字体颜色
    p.setColor(QPalette::WindowText, Qt::white);
//    p.setColor(QPalette::Window, "#0081ff");
    this->setPalette(p);
}

QString management::sendModel1()
{
    QJsonObject obj;
    QJsonObject head;
    head.insert("model", 1);
    obj.insert("head", head);
    obj.insert("body", NULL);
    QJsonDocument doc(obj);
    return doc.toJson();
}

bool management::parseModel1(QByteArray rowData)
{
    // 转成结构体
    Mode1 data = Mode1(rowData);
    /* 设置表格标题行(输入数据为QStringList类型) */
    // 获取起始地址
    QJsonArray::iterator begin = data.field.begin();
    for(QJsonArray::iterator it = begin;it != data.field.end();it++)
    {
        // 加入到字段
        m_strList << (*it).toString();
    }
    /* 创建数据模型 */
    item_mode = new QStandardItemModel();
    // 设置表头
    item_mode->setHorizontalHeaderLabels(m_strList);
    /* 加载共i行数据，并每行有j列数据 */
    for (int i = 0; i < data.body.size(); i++) {
        // 获取第一条数据
        QJsonObject obj = data.body[i].toObject();
         for(int j = 0;j < m_strList.size(); j++)
         {
             item_mode->setItem(i, j, new QStandardItem(obj.value(m_strList[j]).toString()));
         }
    }

    /* 自适应所有列，让它布满空间 */
    ui->People->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    /* 设置表格视图大小 */
    ui->People->resize(850, 400);
    /* 设置表格视图数据 */
    ui->People->setModel(item_mode);
    //设置自动排序
    ui->People->setSortingEnabled(true);
    // 隐藏行号
    QHeaderView* headerView = ui->People->verticalHeader();
    headerView->setHidden(true);
    return data.err == 0;
}

QString management::sendModel2(QStandardItemModel*& model)
{
    int num = model->rowCount();
    QJsonObject obj;
    QJsonObject head;
    QJsonArray headArr;
    QJsonArray bodyArr;
    head.insert("model", 2);
    // 添加头字段数据
    for(int i= 0;i < m_strList.size();++i)
    {
        headArr.append(m_strList[i]);
    }
    head.insert("field", headArr);
    obj.insert("head", head);
    for(int i = 0; i<num;i++)
    {
        QJsonObject tmp;
        for(int j=0;j<m_strList.size();++j)
        {
            QStandardItem * item = model->item(i, j);
            tmp.insert(m_strList[i], item->text());
        }
        bodyArr.append(tmp);
    }
    obj.insert("body", bodyArr);
    QJsonDocument doc(obj);
    return doc.toJson();
}

bool management::parseModel2(QByteArray rowData)
{
    // 转成结构体
    Mode2 data = Mode2(rowData);
    return data.err == 0;
}

QString management::sendModel3(QString id)
{
    QJsonObject obj;
    QJsonObject head;
    QJsonObject body;
    head.insert("model", 3);
    obj.insert("head", head);
    body.insert("id", id);
    obj.insert("body", body);
    QJsonDocument doc(obj);
    return doc.toJson();
}

QString management::sendModel4(QString user, QString pwd)
{
    QJsonObject obj;
    QJsonObject head;
    QJsonObject body;
    head.insert("model", 4);
    obj.insert("head", head);
    body.insert("user", user);
    body.insert("password", pwd);
    obj.insert("body", body);
    QJsonDocument doc(obj);
    return doc.toJson();
}

void management::mouseMoveEvent(QMouseEvent *event)
{
    if(mouse_press)
    {
        move(event->globalPos() - mousePoint);
    }
}

void management::mousePressEvent(QMouseEvent *event)
{
    // 如果点击鼠标左键
    if(event->button() == Qt::LeftButton){
        mouse_press = true;
        // 鼠标点击的位置 - 窗口坐标
        mousePoint = event->globalPos() - this->pos();
    }
    if(event->button() == Qt::RightButton)
    {
        // 添加按钮
        this->addAction(m_action);
        // 显示按钮
        setContextMenuPolicy(Qt::ActionsContextMenu);
    }
}

void management::mouseReleaseEvent(QMouseEvent*)
{
    mouse_press = false;
}
